<template>
  <!-- <el-form-item label="上传人姓名" prop="uploaderName">
       <el-input v-model="uploaderName" minlength="1" maxlength="15" placeholder="不填默认为null"
         aria-valuemax="null" />
     </el-form-item> -->
  <h4>文件上传：</h4>

 <img v-if="Image" :src="Image" class="avatar" />

  <!-- :auto-upload="false" -->
  <el-upload ref="uploadRef" class="upload-demo" :http-request="httpupload" :before-upload="beforeUpload"
    :on-success="uploadSuccess">
   
    <!-- <el-icon v-else class="avatar-uploader-icon">
      <Plus />
    </el-icon> -->
    <template #trigger>
      <el-button type="primary">选择文件</el-button>
    </template>

    <el-button class="ml-3" type="success" @click="clear">
      清除数据
    </el-button>

    <template #tip>
      <div class="el-upload__tip">
        jpg/png 文件的大小要小于500kb
      </div>
    </template>
  </el-upload>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import type { UploadInstance } from 'element-plus'
import { GoodUploadService } from '@/api/Goodinfo.js';
import { imageStore } from '@/store/image.js'
import { ElMessage } from 'element-plus'


const imageInfoStore = imageStore();
const Image = ref(imageInfoStore.info)
const uploadRef = ref<UploadInstance>()

//  const submitUpload = () => {
//    console.log("提交" + uploadRef.value!)
//    uploadRef.value!.submit()
//  }

const beforeUpload = (data) => {
  console.log("data属性:" + data)
}

const httpupload = async (option) => {

  let formData = new FormData()
  // 在formData中加入我们需要的参数
  formData.append('image', option.file)
  //  formData.append('uploaderName',uploaderName.value)
  let result = await GoodUploadService(formData)

  console.log(result)
  uploadSuccess(result)

  imageInfoStore.setInfo(result.data)

  if (result.code === 1) {
    ElMessage.success(result.msg ? result.msg : '上传成功')

  } else {
    ElMessage.error('上传失败')
  }
}

//图片上传成功的回调
const uploadSuccess = (result) => {
  //回显图片
  Image.value = result.data
}
const clear = () => {
  imageInfoStore.removeInfo()
  Image.value = ''
}

</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>